import re
from datetime import datetime
import json
import requests
from bs4 import BeautifulSoup
from matplotlib import *
import matplotlib.pyplot as plt
from urllib.parse import unquote
import numpy as np

plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
class Ordinary_Honour:
    # 进行演员的信息重定向链接爬取，导出txt
    def get_actor_href_list_to_txt(self):
        try:
            url = "https://baike.baidu.com/item/%E5%B9%B3%E5%87%A1%E7%9A%84%E8%8D%A3%E8%80%80/22358681?fromModule=lemma-qiyi_sense-lemma"
            req = requests.get(url=url)  # 进行URL网页请求
            soup = BeautifulSoup(
                req.content, from_encoding="utf-8", features="lxml"
            )  # 使用BeautifulSoup进行网页内容解析
            results = (
                soup.find("body")
                .find("div", {"class": "drama-actor"})
                .find_all("a", recursive=True)  # recursive=True是开启子孙结点，检索。
            )  # 通过BeautifulSoup进行网页内容解析
            href_set = set()
            for result in results:
                # result1 = unquote(result["href"].split("/")[2], "utf-8")，测试代码，查看有重定向链接的演员
                # 是否全部爬取完毕
                href = result.get("href")
                # +" " + result1
                if href is not None:
                    href_set.add(href)  # set去重
            # for result in results:
            #     last_result = result["href"]
            #     href_set.add(last_result)
            with open(
                "actor_href_list.txt", "w", encoding="UTF-8"
            ) as f:  # 将所有演员的信息重定向链接，以文件的形式储存
                for href in href_set:
                    f.write(href + "\n")
                    f.flush()
        except:
            print("请确认网络是否正常！如果网络正常，重新运行。（被反爬了Q&Q）")

    # 进行演员的信息重定向链接爬取，导出JSON
    def get_actor_href_list_to_json(self):
        try:
            url = "https://baike.baidu.com/item/%E5%B9%B3%E5%87%A1%E7%9A%84%E8%8D%A3%E8%80%80/22358681?fromModule=lemma-qiyi_sense-lemma"
            req = requests.get(url=url)  # 进行URL网页请求
            soup = BeautifulSoup(
                req.content, from_encoding="utf-8", features="lxml"
            )  # 使用BeautifulSoup进行网页内容解析
            results = (
                soup.find("body")
                .find("div", {"class": "drama-actor"})
                .find_all("a", recursive=True)  # recursive=True是开启子孙结点，检索。
            )  # 通过BeautifulSoup进行网页内容解析
            href_dict = dict()
            for result in results:
                result1 = unquote(result["href"].split("/")[2], "utf-8")
                # 是否全部爬取完毕
                href_dict[result1] = result["href"]
                # +" " + result1
            actor_href_to_json = []
            for item in href_dict.items():
                test_dict = dict()
                test_dict[item[0]] = item[1]
                actor_href_to_json.append(test_dict)

            with open(
                "actor_href_list.json", "w", encoding="UTF-8"
            ) as f:  # 将所有演员的信息重定向链接，以文件的形式储存
                json.dump(actor_href_to_json, f, ensure_ascii=False, indent=4)
        except:
            print("请确认网络是否正常！如果网络正常，重新运行。（被反爬了Q&Q）")

    # 进行演员信息的链接拼接函数编写,并且导出双函数
    def get_actors_information_json_and_txt(self):
        # 打开已存储演员信息重定向链接的文件
        with open("actor_href_list.txt", "r", encoding="UTF-8") as f_r:
            s_href = f_r.read()
            f_r.flush()
        # 创建纯演员信息重定向链接列表，之前存入文件时是每段末位均有换行符，所以使用\n进行切割标志
        s_href_list = s_href.split("\n")
        href_results = []
        for result in s_href_list:
            # 将重定向链接和主链接拼接成完整可用的链接，添加到列表中
            href_results.append("https://baike.baidu.com" + result)
        for href_result in href_results:
            # 从列表中取出完整的演员信息链接，进行演员信息爬取
            self.__get_actor_json(href_result)
        self.__last_wash_actor_list_file_to_txt()  # 导出Txt文件
        self.__Json_format_flie_to_Json()  # 导出JSON文件

    # 爬取演员信息的私有函数
    def __get_actor_json(self, url):
        try:
            req = requests.get(url=url)
            soup = BeautifulSoup(req.content, from_encoding="UTF-8", features="lxml")
            lonely_actor_list = []
            actor_information_dict = {}
            for x, x1 in zip(
                soup.find_all("dt", {"id": "basic-name"}, recursive=True),
                soup.find_all("dd", {"class": "basicInfo-item value"}, recursive=True),
            ):  # 联合for循环
                actor_information_dict.clear()
                x_str = str(x.text)
                x1_str = str(x1.text)
                # 进行简单数据的清洗，去除杂质符"\\xa0"，"\n"
                x_str = x_str.replace("\xa0", "")
                x1_str = x1_str.replace("\n", "")
                actor_information_dict[x_str] = x1_str
                lonely_actor_list.append(actor_information_dict)
                # 这一步是将一个演员的所有信息，加入到一个列表中，方便管理查看
                # lonely_actor_list.append(x_str + ":" + x1_str)
                # 上述方法与爬取演员重定向链接的逻辑方式一致
            with open("actor_information_list.json", "a", encoding="UTF-8") as f_w:
                # f_w.write(str(lonely_actor_list) + "\n")
                json.dump(lonely_actor_list, f_w, ensure_ascii=False, indent=4)
                # f_w.flush()
            return lonely_actor_list
        except:
            print("请确认网络是否正常！如果网络正常，重新运行。（被反爬了Q&Q）")
            return None

    # 数据清洗的私有函数，并且将清新完毕的数据进行保存
    def __last_wash_actor_list_file_to_txt(self):
        # 将初始爬取的演员信息读取出来
        with open("actor_information_list.txt", "r", encoding="UTF-8") as f:
            s = f.read()
            f.flush()
            # 以末位的"\n"作为切割符，形成一个所有演员信息的嵌套列表结构，[[演员1的信息],...,[演员n的信息],...]
            s = s.split("\n")
            result2 = ""
        for result1 in s:
            pattern = r"\[\d+\]"
            replacement = ""
            result = re.sub(pattern, replacement, result1)  # 正则表达式，去除[]中有数字的格式乱码，
            # sub是一个正则表达式的替换函数
            result = result.replace("\\xa0", "")  # 去除乱码"\\xa0"
            result2 += result + "\n"  # 进行字符串拼接，末位拼接"\n"，方便读取时取用管理
        # 进行清洗完的数据结果重新写入文件
        with open("actor_information_list.txt", "w", encoding="UTF-8") as f_w:
            f_w.write(result2)
            f_w.flush()

    # 导出JSON文件
    def __Json_format_flie_to_Json(self):
        with open("actor_information_list.txt", "r", encoding="UTF-8") as f_r:
            actor_information = f_r.read()
            f_r.flush()
        actor_informations = actor_information.split("\n")  # 对读取的字符串切割成列表
        actor_information1_list_total = []
        for actor_information1 in actor_informations:
            actor_information1_list = (
                actor_information1.replace("[", "").replace("]", "").split(",")
            )  # 简单清洗
            actor_information1_list1 = []
            for actor_information2 in actor_information1_list:
                # 进行JSON格式的构建
                actor_information_dict = {}
                if len(actor_information2.replace("'", "").split(":")) > 1:
                    actor_information_dict[
                        actor_information2.replace("'", "")
                        .split(":")[0]
                        .replace(" ", "")
                    ] = actor_information2.replace("'", "").split(":")[1]
                actor_information1_list1.append(actor_information_dict)
            actor_information1_list_total.append(actor_information1_list1)
        with open("actor_information_list.json", "w", encoding="UTF-8") as f_w:
            json.dump(
                actor_information1_list_total, f_w, ensure_ascii=False, indent=4
            )  # JSON文件写出

    # 明星年龄分布柱状图
    def draw_start_age_bar(self):
        actor_age_list1, actor_age_num_list = self.__Extract_Information_born_date()
        plt.bar(actor_age_list1, actor_age_num_list)
        plt.xlabel("年龄")
        plt.ylabel("同龄明星数量")
        plt.title("年龄柱状图")
        plt.savefig("演员年龄同龄人数量柱状图.png")
        plt.show()

    # 生成演员年龄列表和同龄演员数量列表的函数
    def __Extract_Information_born_date(self):
        with open("actor_information_list.txt", "r", encoding="UTF-8") as f_r:
            datas = f_r.read()
        datas = datas.split("\n")
        actor_age_list = []
        for data in datas:
            if len(data) > 1:
                datas1 = (
                    data.replace("[", "")
                    .replace("]", "")
                    .replace("'", "")
                    .replace(" ", "")
                    .split(",")
                )
                for data1 in datas1:
                    if data1.count("出生日期"):
                        if data1.split(":")[1].count("年"):
                            year = int(datetime.now().date().year)
                            actor_age_list.append(year - int(data1.split(":")[1][0:4]))
        actor_age_list.sort()
        actor_age_num_set = set()
        actor_age_num_list = []  # 年龄相同的人的数量
        for actor_age in actor_age_list:
            actor_age_num_set.add(
                str(actor_age_list.count(actor_age)) + ":" + str(actor_age)
            )
        actor_age_list1 = []  # 最终的年龄列表
        actor_age_num_set_list = list(actor_age_num_set)
        actor_age_num_set_list.sort(key=lambda x: x.split(":")[1])
        for actor_age in actor_age_num_set_list:
            actor_age_list1.append(actor_age.split(":")[1])
            actor_age_num_list.append(actor_age.split(":")[0])
        actor_age_list1 = [int(actor_age) for actor_age in actor_age_list1]
        actor_age_num_list = [int(actor_num) for actor_num in actor_age_num_list]
        return actor_age_list1, actor_age_num_list

    # 演员体重分布的饼图
    def draw_star_weight_pie(self):
        weight = self.__Extract_the_safe_weight_list()
        labels = ["<=50Kg", "50-55Kg", "55-65Kg", ">65Kg"]
        explode = [0.1, 0, 0, 0]
        plt.pie(weight, explode=explode, labels=labels, autopct="%1.1f%%")
        plt.title("演员的体重分布")
        plt.axis("equal")
        plt.legend(loc=4)
        plt.savefig("演员体重分布饼状图.png")
        plt.show()

    # 对提取完演员体重信息，进行进一步分布处理加工的函数
    def __Extract_the_safe_weight_list(self):
        actor_weight_list = self.__Extract_Celebrity_Information("体重", 3, 5)
        weight_count_little_or_eq_50 = 0
        weight_count_q50z55 = 0
        weight_count_q55z65 = 0
        weight_count_big65 = 0
        for actor_weight in actor_weight_list:
            if int(actor_weight) <= 50:
                weight_count_little_or_eq_50 += 1
            elif int(actor_weight) < 55 and int(actor_weight) > 50:
                weight_count_q50z55 += 1
            elif int(actor_weight) >= 55 and int(actor_weight) < 65:
                weight_count_q55z65 += 1
            elif int(actor_weight) >= 65:
                weight_count_big65 += 1
        weight = [
            weight_count_little_or_eq_50,
            weight_count_q50z55,
            weight_count_q55z65,
            weight_count_big65,
        ]
        return weight

    # 演员的年龄直方图
    def draw_Star_age_hsit(self):
        actor_year_list1, actor_age_num_list = self.__Extract_Star_start_age_hsit_list()
        bins = np.around(
            np.linspace(min(actor_year_list1), max(actor_year_list1), 20, endpoint=True)
        )
        plt.hist(
            actor_year_list1,
            bins=bins,
            weights=actor_age_num_list,
            edgecolor="black",
            alpha=0.5,
            color="red",
        )
        plt.xlabel("出生年份")
        plt.ylabel("频率")
        plt.title("出生年份频率分布直方图")
        plt.savefig("出生年份频率分布直方图.png")
        plt.show()

    # 提取演员出生年份，并进行频率分析的函数
    def __Extract_Star_start_age_hsit_list(self):
        with open("actor_information_list.txt", "r", encoding="UTF-8") as f_r:
            datas = f_r.read()
        datas = datas.split("\n")
        actor_age_list = []
        for data in datas:
            if len(data) > 1:
                datas1 = (
                    data.replace("[", "")
                    .replace("]", "")
                    .replace("'", "")
                    .replace(" ", "")
                    .split(",")
                )
                for data1 in datas1:
                    if data1.count("出生日期"):
                        if data1.split(":")[1].count("年"):
                            actor_age_list.append(int(data1.split(":")[1][0:4]))
                        actor_age_list.sort()
                        actor_age_num_set = set()
                        actor_age_num_list = []  # 年龄相同的人的数量
                        for actor_age in actor_age_list:
                            actor_age_num_set.add(
                                str(actor_age_list.count(actor_age))
                                + ":"
                                + str(actor_age)
                            )
                        actor_age_list1 = []  # 最终的年龄列表
                        actor_age_num_set_list = list(actor_age_num_set)
                        actor_age_num_set_list.sort(key=lambda x: x.split(":")[1])
                        for actor_age in actor_age_num_set_list:
                            actor_age_list1.append(actor_age.split(":")[1])
                            actor_age_num_list.append(actor_age.split(":")[0])
        actor_age_list1 = [int(age) for age in actor_age_list1]
        actor_age_num_list = [int(num) for num in actor_age_num_list]
        return actor_age_list1, actor_age_num_list

    # 提取爬取演员信息的获取函数(粗略提取，需要根据提取之后的列表再加工)
    def __Extract_Celebrity_Information(self, key_, stay_num1, stay_num2):
        with open("actor_information_list.txt", "r", encoding="UTF-8") as f_r:
            datas = f_r.read()
        datas = datas.split("\n")
        actor__list = []
        for data in datas:
            if len(data) > 1:
                datas1 = (
                    data.replace("[", "")
                    .replace("]", "")
                    .replace("'", "")
                    .replace(" ", "")
                    .split(",")
                )
                for data1 in datas1:
                    if data1.count(key_):
                        actor__list.append(data1[stay_num1:stay_num2])
        return actor__list

    # 体重饼图和年龄柱图创建函数
    def draw_one_zhu_pie_double_pic(self):
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
        weight = self.__Extract_the_safe_weight_list()
        labels = ["<=50Kg", "50-55Kg", "55-65Kg", ">65Kg"]
        explode = [0.1, 0, 0, 0]
        ax1.pie(weight, explode=explode, labels=labels, autopct="%1.1f%%")
        ax1.set_title("演员的体重分布")
        ax1.axis("equal")
        ax1.legend(loc=4)
        actor_age_list1, actor_age_num_list = self.__Extract_Information_born_date()
        ax2.bar(actor_age_list1, actor_age_num_list)
        ax2.set_xlabel("年龄")
        ax2.set_ylabel("同龄明星数量")
        ax2.set_title("年龄柱状图")
        plt.tight_layout()
        plt.title("体重饼图和年龄柱图")
        plt.savefig("体重饼图和年龄柱图.png")
        plt.show()

    # 三个图一并绘制
    def draw_one_zhu_hsit_pie_third_pic(self):
        # 创建图形和子图
        fig = plt.figure(figsize=(15, 15))  # figsize设置画布尺寸，英寸的大小
        plt.gca().remove()
        plt.title("三图对照")
        # 划分子图区域
        ax1 = plt.subplot2grid(
            (2, 2), (0, 0), colspan=1
        )  # grid的布局格式，shape(3, 2)：指定网格布局的行数和列数，这里是自己设置3行2列的表格。
        ax2 = plt.subplot2grid((2, 2), (0, 1))
        ax3 = plt.subplot2grid(
            (2, 2),
            (1, 0),
            colspan=2,
        )
        # 柱状图
        actor_age_list1, actor_age_num_list = self.__Extract_Information_born_date()
        ax1.bar(actor_age_list1, actor_age_num_list)
        ax1.set_xlabel("年龄")
        ax1.set_ylabel("同龄明星数量")
        ax1.set_title("年龄柱状图")
        # 饼状图
        weight = self.__Extract_the_safe_weight_list()
        labels = ["<=50Kg", "50-55Kg", "55-65Kg", ">65Kg"]
        explode = [0.1, 0, 0, 0]
        ax2.pie(weight, explode=explode, labels=labels, autopct="%1.1f%%")
        ax2.set_title("演员的体重分布")
        ax2.axis("equal")
        ax2.legend(loc=4)
        # 频率直方图
        actor_year_list1, actor_age_num_list = self.__Extract_Star_start_age_hsit_list()
        bins = np.around(
            np.linspace(min(actor_year_list1), max(actor_year_list1), 20, endpoint=True)
        )
        # 频率直方图绘制
        ax3.hist(
            actor_year_list1,
            bins=bins,
            weights=actor_age_num_list,
            edgecolor="black",
            alpha=0.5,
            color="red",
        )
        # 设置x轴的标签
        ax3.set_xlabel("出生年份")
        # 设置y轴的标签
        ax3.set_ylabel("频率")
        # 设置标题
        ax3.set_title("出生年份频率分布直方图")
        # 自适应边距
        plt.tight_layout()
        # 保存图片
        plt.savefig("三图对照.png")
        plt.show()

    # 导出收视率的txt文件
    def get_TV_rate_to_txt(self):
        try:
            url = "https://baike.baidu.com/item/%E5%B9%B3%E5%87%A1%E7%9A%84%E8%8D%A3%E8%80%80/22358681"
            req = requests.get(url)
            soup = BeautifulSoup(req.content, "lxml")
            text = soup.find_all("div", attrs={"label-module": "para"})
            text = [str(s.text) for s in text]
            Tv_rate_text = text[91:259]
            Bo_chu_ri_qi = []
            ZheJiang_Tv_rate = []
            East_TV_fen_e = []
            ZheJIang_TV_fen_e = []
            East_Tv_rate = []
            East_tv_rand = []
            ZheJiang_tv_rand = []
            for rate in range(0, len(Tv_rate_text), 7):
                Bo_chu_ri_qi.append(Tv_rate_text[rate])
            for rate in range(1, len(Tv_rate_text), 7):
                East_Tv_rate.append(Tv_rate_text[rate])
            for rate in range(2, len(Tv_rate_text), 7):
                East_TV_fen_e.append(Tv_rate_text[rate])
            for rate in range(3, len(Tv_rate_text), 7):
                East_tv_rand.append(Tv_rate_text[rate])
            for rate in range(4, len(Tv_rate_text), 7):
                ZheJiang_Tv_rate.append(Tv_rate_text[rate])
            for rate in range(5, len(Tv_rate_text), 7):
                ZheJIang_TV_fen_e.append(Tv_rate_text[rate])
            for rate in range(6, len(Tv_rate_text), 7):
                ZheJiang_tv_rand.append(Tv_rate_text[rate])
            with open("收视率.txt", "w", encoding="Utf-8") as f_w:
                f_w.write(
                    str(Bo_chu_ri_qi)
                    + "\n"
                    + str(East_Tv_rate)
                    + "\n"
                    + str(East_TV_fen_e)
                    + "\n"
                    + str(East_tv_rand)
                    + "\n"
                    + str(ZheJiang_Tv_rate)
                    + "\n"
                    + str(ZheJIang_TV_fen_e)
                    + "\n"
                    + str(ZheJiang_tv_rand)
                )
                f_w.flush()
        except:
            print("请确认网络是否正常！如果网络正常，重新运行。（被反爬了Q&Q）")

    # 提取爬取收视率方面的信息
    def __Extract_data(self):
        with open("收视率.txt", "r", encoding="UTf-8") as f_r:
            rate_list = f_r.read().split("\n")
            rate_list1 = rate_list[0:4]
            rate_list2 = rate_list[4:8]
            f_r.flush()
        Bo_chu_ri_qi = (
            rate_list1[0].replace("[", "").replace("]", "").replace("'", "").split(",")
        )
        Bo_chu_ri_qi = [s.replace(" ", "") for s in Bo_chu_ri_qi]
        East_Tv_rate = (
            rate_list1[1].replace("[", "").replace("]", "").replace("'", "").split(",")
        )
        East_Tv_rate = [s.replace(" ", "") for s in East_Tv_rate]
        East_TV_fen_e = (
            rate_list1[2].replace("[", "").replace("]", "").replace("'", "").split(",")
        )
        East_TV_fen_e = [s.replace(" ", "") for s in East_TV_fen_e]
        East_tv_rand = (
            rate_list1[3].replace("[", "").replace("]", "").replace("'", "").split(",")
        )
        East_tv_rand = [s.replace(" ", "") for s in East_tv_rand]
        ZheJIang_Tv_rate = (
            rate_list2[0].replace("[", "").replace("]", "").replace("'", "").split(",")
        )
        ZheJIang_Tv_rate = [s.replace(" ", "") for s in ZheJIang_Tv_rate]
        ZHeJiang_TV_fen_e = (
            rate_list2[1].replace("[", "").replace("]", "").replace("'", "").split(",")
        )
        ZHeJiang_TV_fen_e = [s.replace(" ", "") for s in ZHeJiang_TV_fen_e]
        ZheJIang_tv_rand = (
            rate_list2[2].replace("[", "").replace("]", "").replace("'", "").split(",")
        )
        ZheJIang_tv_rand = [s.replace(" ", "") for s in ZheJIang_tv_rand]
        wan_zheng_list = [
            Bo_chu_ri_qi,
            East_Tv_rate,
            East_TV_fen_e,
            East_tv_rand,
            ZheJIang_Tv_rate,
            ZHeJiang_TV_fen_e,
            ZheJIang_tv_rand,
        ]
        return wan_zheng_list

    # 对txt文件进行JSON格式转换
    def __Json_format(self, province, Bo_chu_ri_qi, Tv_rate, TV_fen_e, Tv_rand):
        East_dict = {}
        East_data_list = []
        for n, x, x1, x2 in zip(Bo_chu_ri_qi, Tv_rate, TV_fen_e, Tv_rand):
            East_data_list.clear()
            dict_test = {}
            dict_test[f"{province}卫视收视率"] = x
            East_data_list.append(dict_test)
            dict_test1 = {}
            dict_test1[f"{province}卫视收视份额"] = x1
            East_data_list.append(dict_test1)
            dict_test3 = {}
            dict_test3[f"{province}卫视收视排名"] = x2
            East_data_list.append((dict_test3))
            East_dict[n] = East_data_list
        return East_dict

    # 导出收视率的JSON文件
    def get_Tv_rate_to_json(self):
        Bo_chu_ri_qi = self.__Extract_data()[0]
        East_Tv_rate = self.__Extract_data()[1]
        East_TV_fen_e = self.__Extract_data()[2]
        East_tv_rand = self.__Extract_data()[3]
        ZheJIang_Tv_rate = self.__Extract_data()[4]
        ZHeJiang_TV_fen_e = self.__Extract_data()[5]
        ZheJIang_tv_rand = self.__Extract_data()[6]
        East = self.__Json_format(
            "东方", Bo_chu_ri_qi, East_Tv_rate, East_TV_fen_e, East_tv_rand
        )
        Zhejiang = self.__Json_format(
            "浙江", Bo_chu_ri_qi, ZheJIang_Tv_rate, ZHeJiang_TV_fen_e, ZheJIang_tv_rand
        )
        East_dict = {}
        Zhejiang_dict = {}
        East_dict["东方卫视CSM59城收视"] = East
        Zhejiang_dict["浙江卫视CSM59城收视"] = Zhejiang
        Total_list = [East_dict, Zhejiang_dict]
        with open("收视率.json", "w", encoding="UTF-8") as f_r:
            json.dump(Total_list, f_r, ensure_ascii=False, indent=4)

    # 绘制东方卫视收视率的折线图
    def draw_East_ZheXian(self):
        plt.subplots(figsize=(13, 13))
        Bo_chu_ri_qi = self.__Extract_data()[0]
        East_Tv_rate = self.__Extract_data()[1]
        East_Tv_rate = [float(rate) for rate in East_Tv_rate]
        plt.plot(
            Bo_chu_ri_qi,
            East_Tv_rate,
            marker="H",
            markersize=8,
            linestyle="-",
            linewidth=2,
            color="black",
        )
        # 设置x轴标签角度为垂直
        plt.xticks(rotation="vertical")
        plt.title("东方卫视收视率折线图")
        plt.xlabel("播放日期")
        plt.ylabel("收视率")
        plt.savefig("东方卫视收视率-折线图.png")
        plt.show()

    # 绘制浙江卫视收视率的折现图
    def draw_ZheJiang_ZheXian(self):
        fig = plt.subplots(figsize=(13, 13))
        Bo_chu_ri_qi = self.__Extract_data()[0]
        ZheJiang_Tv_rate = self.__Extract_data()[4]
        ZheJiang_Tv_rate = [float(rate) for rate in ZheJiang_Tv_rate]
        plt.plot(
            Bo_chu_ri_qi,
            ZheJiang_Tv_rate,
            marker="P",
            markersize=8,
            linestyle="-",
            linewidth=2,
        )
        # 设置x轴标签角度为垂直
        plt.xticks(rotation="vertical")
        plt.title("浙江卫视收视率折线图")
        plt.xlabel("播放日期")
        plt.ylabel("收视率")
        plt.savefig("浙江卫视收视率-折线图.png")
        plt.show()

    # 一个图上有浙江和东方收视率的双子图
    def draw_double_East_Zhejiang_zhexian(self):
        Bo_chu_ri_qi = self.__Extract_data()[0]
        East_Tv_rate = self.__Extract_data()[1]
        ZheJiang_Tv_rate = self.__Extract_data()[4]

        East_Tv_rate = [float(rate) for rate in East_Tv_rate]
        ZheJiang_Tv_rate = [float(rate) for rate in ZheJiang_Tv_rate]
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 10))

        ax1.plot(
            Bo_chu_ri_qi,
            East_Tv_rate,
            marker="H",
            markersize=8,
            linestyle="-",
            linewidth=2,
            color="black",
        )
        # 设置x轴标签角度为垂直
        ax1.set_xticklabels(Bo_chu_ri_qi, rotation=90)
        ax1.set_title("东方卫视收视率折线图")
        ax1.set_xlabel("播放日期")
        ax1.set_ylabel("收视率")
        ax2.plot(
            Bo_chu_ri_qi,
            ZheJiang_Tv_rate,
            marker="P",
            markersize=8,
            linestyle="-",
            linewidth=2,
        )
        # 设置x轴标签角度为垂直
        ax2.set_xticklabels(Bo_chu_ri_qi, rotation=90)
        ax2.set_title("浙江卫视收视率折线图")
        ax2.set_xlabel("播放日期")
        ax2.set_ylabel("收视率")
        plt.savefig("浙江和东方卫视收视率-折线图.png")
        plt.show()

    # 一个图上有两个卫视收视率的折现图
    def draw_one_pic_East_and_Zhejiang_Xian(self):
        Bo_chu_ri_qi = self.__Extract_data()[0]
        East_Tv_rate = self.__Extract_data()[1]
        ZheJiang_Tv_rate = self.__Extract_data()[4]

        East_Tv_rate = [float(rate) for rate in East_Tv_rate]
        ZheJiang_Tv_rate = [float(rate) for rate in ZheJiang_Tv_rate]
        fig = plt.subplots(figsize=(16, 10))

        plt.plot(
            Bo_chu_ri_qi,
            East_Tv_rate,
            marker="H",
            markersize=8,
            linestyle="-",
            linewidth=2,
            color="red",
            label="东方卫视收视率",
        )
        plt.plot(
            Bo_chu_ri_qi,
            ZheJiang_Tv_rate,
            marker="P",
            markersize=8,
            linestyle="-",
            linewidth=2,
            label="浙江卫视收视率",
        )
        # 设置x轴标签角度为垂直
        plt.xticks(Bo_chu_ri_qi, rotation=90)
        plt.title("东方卫视和浙江卫视收视率折线图")
        plt.xlabel("播放日期")
        plt.legend(loc=2)
        plt.ylabel("收视率")
        plt.savefig("浙江卫视和东方卫视收视率-折线图.png")
        plt.show()

    # 有两个卫视的收视率的柱状图
    def draw_double_East_Zhejiang_TV_rates_pic(self):
        Bo_chu_ri_qi = self.__Extract_data()[0]
        East_Tv_rate = self.__Extract_data()[1]
        ZheJiang_Tv_rate = self.__Extract_data()[4]
        East_Tv_rate = [float(rate) for rate in East_Tv_rate]
        ZheJiang_Tv_rate = [float(rate) for rate in ZheJiang_Tv_rate]

        # 设置柱状图的宽度
        bar_width = 0.35

        # 绘制复式柱状图
        fig, ax = plt.subplots()
        ax.bar(range(len(Bo_chu_ri_qi)), East_Tv_rate, width=bar_width, label="东方卫视收视率")
        ax.bar(
            [x + bar_width for x in range(len(Bo_chu_ri_qi))],
            ZheJiang_Tv_rate,
            width=bar_width,
            label="浙江卫视收视率",
        )

        # 设置 x 坐标轴标签和标题
        ax.set_ylabel("收视率")
        ax.set_title("东方卫视和浙江卫视收视率复式柱状图")

        # 设置 x 坐标轴刻度和标签
        plt.xticks(rotation=90)
        ax.set_xticks(range(len(Bo_chu_ri_qi)))
        ax.set_xticklabels(Bo_chu_ri_qi)

        # 添加图例
        ax.legend(loc=2)

        # 展示图形
        plt.tight_layout()
        plt.savefig("东方卫视和浙江卫视收视率复式柱状图.png")
        plt.show()

    # 一个图里面有上面四个子图(东方折线，浙江折线，一图双折线，一图双柱)
    def draw_four_pic_oneEastLine_oneZhejiangLine_doubleEastZhejiangLine_fushizhu(self):
        Bo_chu_ri_qi = self.__Extract_data()[0]
        East_Tv_rate = self.__Extract_data()[1]
        ZheJiang_Tv_rate = self.__Extract_data()[4]
        East_Tv_rate = [float(rate) for rate in East_Tv_rate]
        ZheJiang_Tv_rate = [float(rate) for rate in ZheJiang_Tv_rate]
        # 创建图形和子图
        fig = plt.figure(figsize=(20, 20))  # figsize设置画布尺寸，英寸的大小
        if plt.gca():
            plt.gca().remove()
        plt.title("四图同堂")
        # 划分子图区域
        ax1 = plt.subplot2grid(
            (2, 2), (0, 0)
        )  # grid的布局格式，shape(2, 2)：指定网格布局的行数和列数，这里是自己设置3行2列的表格。
        ax2 = plt.subplot2grid((2, 2), (0, 1))
        ax3 = plt.subplot2grid((2, 2), (1, 0))
        ax4 = plt.subplot2grid((2, 2), (1, 1))
        ax1.plot(
            Bo_chu_ri_qi,
            East_Tv_rate,
            marker="H",
            markersize=8,
            linestyle="-",
            linewidth=2,
            color="black",
        )
        # 设置x轴标签角度为垂直
        ax1.set_xticks(range(len(Bo_chu_ri_qi)))
        ax1.set_xticklabels(Bo_chu_ri_qi, rotation=90)
        ax1.set_title("东方卫视收视率折线图")
        ax1.set_xlabel("播放日期")
        ax1.set_ylabel("收视率")
        ax2.plot(
            Bo_chu_ri_qi,
            ZheJiang_Tv_rate,
            marker="P",
            markersize=8,
            linestyle="-",
            linewidth=2,
        )
        # 设置x轴标签角度为垂直
        ax2.set_xticks(range(len(Bo_chu_ri_qi)))
        ax2.set_xticklabels(Bo_chu_ri_qi, rotation=90)
        ax2.set_title("浙江卫视收视率折线图")
        ax2.set_xlabel("播放日期")
        ax2.set_ylabel("收视率")
        # 双折线图
        ax3.plot(
            Bo_chu_ri_qi,
            East_Tv_rate,
            marker="H",
            markersize=8,
            linestyle="-",
            linewidth=2,
            color="red",
            label="东方卫视收视率",
        )
        ax3.plot(
            Bo_chu_ri_qi,
            ZheJiang_Tv_rate,
            marker="P",
            markersize=8,
            linestyle="-",
            linewidth=2,
            label="浙江卫视收视率",
        )
        # 设置x轴标签角度为垂直
        ax3.set_xticks(range(len(Bo_chu_ri_qi)))
        ax3.set_xticklabels(Bo_chu_ri_qi, rotation=90)
        ax3.set_title("东方卫视和浙江卫视收视率折线图")
        ax3.set_xlabel("播放日期")
        ax3.legend(loc=2)
        ax3.set_ylabel("收视率")
        # 设置柱状图的宽度
        bar_width = 0.35
        ax4.bar(
            range(len(Bo_chu_ri_qi)), East_Tv_rate, width=bar_width, label="东方卫视收视率"
        )
        ax4.bar(
            [x + bar_width for x in range(len(Bo_chu_ri_qi))],
            ZheJiang_Tv_rate,
            width=bar_width,
            label="浙江卫视收视率",
        )
        # 设置 x 坐标轴标签和标题
        ax4.set_ylabel("收视率")
        ax4.set_xlabel("播放日期")
        ax4.set_title("东方卫视和浙江卫视收视率复式柱状图")
        # 设置 x 坐标轴刻度和标签
        ax4.set_xticks(range(len(Bo_chu_ri_qi)))
        ax4.set_xticklabels(Bo_chu_ri_qi, rotation=90)
        # 添加图例
        ax4.legend(loc=2)
        plt.xticks(rotation=90)
        # 展示图形
        plt.tight_layout()
        plt.savefig("四图同堂.png")
        plt.show()


if __name__ == "__main__":
    ordinary = Ordinary_Honour()
    ordinary.draw_East_ZheXian()
    # draw开头的函数式画图，get开头的是获取数据的函数
